window.addEventListener("load", function(){

})
var parseRules = {
    "rmdown.com": function(link){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if (xhr.readyState==4){// 4 = "loaded"
                if (xhr.status==200) {// 200 = OK
                    var data = xhr.responseText.match(/<input.*name\s*=\s*["']ref["'].*?value\s*=\s*["'](.*?)["'].*<input.*name\s*=\s*["']reff["'].*?value\s*=\s*["'](.*?)["'].*/i);
                    if(data){
                        (function(data){
                            chrome.extension.sendMessage({"topic":"download","options":{"url":"http://www.rmdown.com/download.php","method":"POST","body":"ref="+data.ref+";reff="+data.reff+"submit=download"}},function(response) {
                                //后台又回复过来的        
                            });
                            // var xhr = new XMLHttpRequest();
                            // xhr.onreadystatechange = function(){
                            //     if (xhr.readyState==4){// 4 = "loaded"
                            //         if (xhr.status==200) {// 200 = OK
                            //             // console.log(xhr.responseText);
                            //         } else {
                            //             var d = xhr;
                            //         }
                            //     }
                            // }
                            // xhr.open("POST","http://www.rmdown.com/download.php",true);
                            // // xhr.setRequestHeader("hash", data.ref);
                            // var formData = new FormData();
                            // formData.append("ref", data.ref);
                            // formData.append("reff", data.reff);
                            // formData.append("submit", data.submit);
                            // xhr.send(formData);
                        })({ref: data[1], reff: data[2], submit: "download"})
                    }
                } else {
                    console.log("bad link:",link);
                }
            }
        }
        xhr.open("GET",link,true);
        xhr.send();
    }
}
$(document).ready(function(){
    if(top === window){
        var domain = document.domain;
        var url = location.href;
        var referrer = document.referrer;

        (function(){
            if(url.match(/cl\.man\.lv\/htm_data.*/)){
                var aEles = $(".tpc_content a");
                if($(".t3:first").find("a").eq(1).attr("href").match(/fid=21$/)){
                    var downa = aEles.last();
                    util.isUrl(downa.text()) && downa.attr("href", downa.text());
                    var a = util.addFixedPositionLink(downa.text(),$("h4:first").text(),static_imgs.surf);
                    chrome.extension.sendMessage({topic:"resource", cmd:"addDomain", domain:util.getDomain(downa.text())}, function(backMsg){
                        if(backMsg.visitedFlg == 1){
                            var xhr = new XMLHttpRequest();
                            xhr.onreadystatechange = function(){
                                if (xhr.readyState==4){// 4 = "loaded"
                                    if (xhr.status==200) {// 200 = OK
                                        var resptext = xhr.responseText;
                                        var result = resptext.match(/putong.*?<a\s*?href=['"](.*?)['"]/);
                                        if(result){
                                            a.attr("href", result[1]);
                                            a.find("img").attr("src", static_imgs.download);
                                        }
                                    } else {
                                        // alert("Problem retrieving XML data");
                                    }
                                }
                            }
                            xhr.open("GET",downa.text().replace("file-","down-"),true);
                            xhr.send();
                        }
                    });
                }else if($(".t3:first").find("a").eq(1).attr("href").match(/fid=(2|4|5|15)$/)){
                    var downUrl = "";
                    aEles.each(function(i, it){
                        if($(it).text().indexOf("rmdown")>0) downUrl = $(it).text();
                    })
                    if(!downUrl) downUrl = aEles.last()[0].href;
                    var a = util.addFixedPositionLink(downUrl,$("h4:first").text(),static_imgs.surf);
                }
            }
        })();



        (function(){
            
            if(url.match(/cl\.man\.lv\/htm_data\/(8|16)/)){
                if($("#pic_wrapper").length == 0){
                    var pic = new PIC();
                    util.addFixedPositionLink(function(){
                        if(!pic.serial || pic.serial.length == 0){
                            var title = document.querySelector("h4").textContent;
                            var imgs = document.querySelectorAll(".tpc_content input[type=image]");
                            var picUrls = [];
                            for(var i = 0; i< imgs.length;i++){
                                picUrls.push(imgs[i].src);
                            }
                            pic.addSerial(title , picUrls);
                        }
                        pic.show("fullscreen");
                    },$("h4:first").text(),static_imgs.fullscreen)
                }
            }
        })();

        (function(){
            $(document).bind("click", function(event){
                if(event.target.id == "reload-button"){
                    chrome.extension.sendMessage({topic:"resource", cmd:"addExpDomain"}, function(){});
                }
            })
        })();
        //showFic

        // (function(){
        //     if(url.match(/cl\.man\.lv\/thread0806\.php/)){
        //         $("#ajaxtable").bind("mouseover", function(event){
        //             setTimeout(function(){
        //                 var a = event.target;
        //                 if(a.tagName == "A" && a.href.match(/cl\.man\.lv\/htm_data\.*/)){
        //                     showPic(a.href)
        //                 }
        //             },100);
        //         })
        //     }
        // })();
        (function(){
            if(url.match(/www\.sufile\.com\/file.*/)){
                var slow_button = document.getElementById("slow_button");
                slow_button.onclick = function(){};
                slow_button.setAttribute("onclick", "function(){}");
                slow_button.addEventListener("click",function(event){
                    var downa = $("<a></a>").appendTo($("body"));
                    downa.attr("href", document.getElementById('downpage_link').href);
                    downa[0].click();
                     event.stopPropagation();
                     event.preventDefault();
                }, true)
            }
        })();
        (function(){
            if(url.match(/www\.dwbpy\.com\/link\.php/)){
                $("form").css({position:"relative",zIndex:"99999999"})
            }
        })();
        //批量下载
        (function(){
            if(url.match(/cl\.man\.lv\/thread0806\.php/)){
                function getRealLink(responseText){
                    var realLink = responseText.match(/>\s*(http:\/\/www\.rmdown\.com\/link\.php.*?)\s*</);
                    if(realLink){
                        realLink = realLink[1];
                    }
                    return realLink;
                }
                var links = [];
                $("#ajaxtable h3 a").each(function(i, it){
                    if(it.href.indexOf("htm_data")>=0){
                        links.push(it.href);
                    }
                })
                // util.batDownload(links, getRealLink);
            }
        })();

        var regResult = url.match(/lepan\.cc\/down-(\d*)\.html/);
        if(regResult){
            window.addEventListener(function(event){
                event.stopPropagation();
            }, true);
            $("#down_box").css("display", "block");
            $("#code_box").css("display", "none");
            chrome.extension.sendMessage({'domain':'lepan.cc','cookie': document.cookie, 'file_id': regResult[1]},function(response) {
                //后台又回复过来的        
            });
        }

        var rules= {
            "lepan.cc":{
                maska:{
                    attr:"id",
                    reg:/__lgUnion_a|__udbpp_a/
                },
                downa:{
                    attr:"className",
                    selector:".fbtn-down a,.putong a"
                }
            },
            "sufile.com":{
                unbind:{
                    selector:"#slow_button"
                }
            }
        }
        var rule = rules[domain];
        if(rule){
            window.addEventListener(function(event){
                event.stopPropagation();
            }, true);
            document.addEventListener(function(event){
                event.stopPropagation();
            }, true);
            document.body.addEventListener(function(event){
                event.stopPropagation();
            }, true);

            document.onclick = function(){var a = "clickPush"};
            document.body.onclick = function(){var a = "clickPush"};
            for(var s in rule){
                if(s.selector){
                    $(s.selector).bind("click", function(event){
                        event.stopPropagation();
                        event.preventDefault();
                    })
                }
            }
            $("a").each(function(i, it){
                var maska = rule.maska;
                var downa = rule.downa;
                if(maska.reg && it[maska.attr].match(maska.reg)){
                    $(it).css("display","none !important");
                }
                if(downa.reg && it[downa.attr].match(downa.reg)){
                    it.addEventListener(function(event){
                        event.stopPropagation();
                        event.preventDefault();
                    }, true)
                }
            })
            if(rule.unbind){
                var unbind = rule.unbind;
                $(unbind.selector).each(function(i, it){
                    it.addEventListener("click", function(event){
                        event.stopPropagation();
                        event.preventDefault();
                    })
                    it.onclick = function(){};
                })
            }
        }
        clmannest.run();
    }
})
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    if(request.topic == "download"){
        if(request.cmd == "add-icon"){
            if(top === window && location.href.match(/cl\.man\.lv/)){
                var a = util.addFixedPositionLink("javascript:void(0)", $("h4:first").text(),static_imgs.download);
                a.bind("click", function(){
                    chrome.extension.sendMessage({"topic":"download","options":{"url":request.url,"method":"GET"}},function(response) {
                        //后台又回复过来的        
                    });

                })
            }
        }
    }
}); 
